package com.best.oasis.settlement.service.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.best.oasis.settlement.common.entity.security.RoleGroup;
import com.best.oasis.settlement.common.entity.security.User;
import com.best.oasis.settlement.common.entity.security.UserGroupMapping;
import com.best.oasis.settlement.common.entity.security.UserRoleMapping;
import com.best.oasis.settlement.common.so.security.UserSO;
import com.best.oasis.settlement.common.vo.security.RoleGroupVO;
import com.best.oasis.settlement.common.vo.security.RoleVO;
import com.best.oasis.settlement.common.vo.security.SelectedRoleGroupVO;
import com.best.oasis.settlement.common.vo.security.UserVO;
import com.best.oasis.settlement.dao.security.RoleDao;
import com.best.oasis.settlement.dao.security.RoleGroupDao;
import com.best.oasis.settlement.dao.security.UserDao;
import com.best.oasis.settlement.service.base.BaseServiceImpl;
import com.best.oasis.settlement.util.Config;
import com.best.oasis.settlement.util.SecurityUtil;
import com.best.oasis.settlement.util.page.PageList;

@Service
public class UserServiceImpl extends BaseServiceImpl<User, UserVO, Long> implements UserService {
	
    @Autowired private UserDao userDao;
    @Autowired private PasswordEncoder passwordEncoder;
    @Autowired private RoleGroupService roleGroupService;
    @Autowired private RoleGroupDao roleGroupDao;
    @Autowired private RoleDao roleDao;
    @Autowired private RoleService roleService;
    @Autowired private AuthenticationManager authManager;
    @Override
    public void afterConstruct(){
        super.setBaseDao(userDao);
        super.setEntityClass(User.class);
        super.setEntityVOClass(UserVO.class);
    }
    @Override
    public UserVO create(UserVO vo){
    	vo.setUserName( vo.getUserName().toUpperCase() );
        UserVO result = super.create(vo);
        UserGroupMapping userGroup;
        UserRoleMapping userRole;
        List<RoleVO> newRoles = new ArrayList<RoleVO>();
        for (RoleGroupVO group:vo.getRoleGroups()){
        	
        	group = roleGroupService.get(group.getId());
        	
            userGroup = new UserGroupMapping();
            userGroup.setUser_Id(result.getId());
            userGroup.setGroup_Id(group.getId());
            userDao.createUserGroup(userGroup);
            for(RoleVO role:group.getRoles()){
                if(!newRoles.contains(role)){
                    newRoles.add(role);
                }
            }
        }
        for(RoleVO role:newRoles){
            userRole = new UserRoleMapping();
            userRole.setUser_Id(result.getId());
            userRole.setRole_Id(role.getId());
            userDao.createUserRole(userRole);
        }
        return result;
    }
    @Override
    public void remove(Long id){
        UserVO vo = get(id);
        userDao.removeUserGroup(vo.getId());
        userDao.removeUserRole(vo.getId());
        super.remove(id);
    }
    @Override
    public void remove(List<Long> ids){
        for(Long id:ids){
            remove(id);
        }
    }
    @Override
    public UserVO update(UserVO vo){
        /**
         * 简单些搞，把之前的关连都删掉，然后再插入新的
         */
		userDao.removeUserGroup(vo.getId());
		userDao.removeUserRole(vo.getId());

		UserGroupMapping userGroup;
		UserRoleMapping userRole;

		List<RoleGroupVO> roleGroups = vo.getRoleGroups();
		List<RoleVO> roles;
		List<RoleVO> newRoles = new ArrayList<RoleVO>();
		 
		if (roleGroups != null && roleGroups.size() > 0) {
			for (RoleGroupVO group : roleGroups) {

				group = roleGroupService.get(group.getId());
				userGroup = new UserGroupMapping();
				userGroup.setUser_Id(vo.getId());
				userGroup.setGroup_Id(group.getId());
				userDao.createUserGroup(userGroup);

				roles = group.getRoles();
				if (roles != null && roles.size() > 0) {
					for (RoleVO role : roles ) {
						if (!newRoles.contains(role)) {
							newRoles.add(role);
						}
					}
				}
			}
		}
		if( newRoles != null && newRoles.size() > 0 ){
			for (RoleVO role : newRoles) {
				userRole = new UserRoleMapping();
				userRole.setUser_Id(vo.getId());
				userRole.setRole_Id(role.getId());
				userDao.createUserRole(userRole);
			}
		}
		
		super.update(vo);
		vo = get( vo.getId() );
        return vo;
    }
    @Override
    public UserVO get(Long id){
        UserVO result = super.get(id);
        if(result!=null){
            List<RoleGroupVO> roleGroups = roleGroupService.getRoleGroupsByUserid(id);
            List<RoleVO> roles = roleService.getRolesByUserID(id);
            result.setRoleGroups(roleGroups);
            result.setRoles(roles);
        }
        return result;
    }
    @Override
    public UserVO getBy(String fieldName,Object value){
        UserVO result = super.getBy(fieldName, value);
        if(result!=null){
            List<RoleGroupVO> roleGroups = new ArrayList<RoleGroupVO>(roleGroupService.getRoleGroupsByUserid(result.getId()));
            List<RoleVO> roles = new ArrayList<RoleVO>(roleService.getRolesByUserID(result.getId()));
            result.setRoleGroups(roleGroups);
            result.setRoles(roles);
        }
        return result;
    }
    
    @SuppressWarnings("unchecked")
	public UserVO getUserByUsername(String username) throws UsernameNotFoundException  {
    	UserVO result = (UserVO)orikaBeanMapper.convert(userDao.getUserByUsername(username), entityVOClass);
        return result;
    }
	/**
	 *新建用户信息
	 */
    public UserVO register(UserVO userVO) {
        UserVO result = null;
		List<RoleVO> newRoles = new ArrayList<RoleVO>();
		if(userVO.getRoleGroups()!=null){			
			for(RoleGroupVO roleGroup :userVO.getRoleGroups()){
				newRoles.addAll(roleGroup.getRoles());
			}
		}
		userVO.setRoles(newRoles);
        userVO.setPassword(passwordEncoder.encodePassword(userVO.getPassword(), null));
        result = save(userVO);    
        return result;
    }
    /**
     * 更新密码
     * @param userVO
     */     
    public boolean updatePassword(UserVO userVO, String oldPassword, String newPassword)
    {
    	boolean result;
    	String encodedPassword = passwordEncoder.encodePassword(oldPassword, null);
    	if(userVO.getPassword().equals(encodedPassword)){
    		userVO.setPassword(passwordEncoder.encodePassword(newPassword, null));
    		simpleUpdate(userVO);
    		result = true;
    	}
    	else{
    		result = false;
    	}
    	return result;
    }

    @Override
    public  UserVO simpleUpdate(UserVO userVO){
    	UserVO result = super.update(userVO);
		return result;
    }
    
	@Override
	public UserVO save(UserVO userVO){
		UserVO result = null;
        if(userVO.getId()!=null && exists(userVO.getId())){
       	 result = update(userVO);
       }else{
       	 result = create(userVO);
       }
		return result;
	}
	/**
	 * 用户管理模块中，用来记录当前用户的用户组
	 * @author bl00575
	 *
	 */
	@Override
	public List<SelectedRoleGroupVO> getSelectedRoleGroup(Long id) {
		List<RoleGroupVO> rolegroupList =new ArrayList<RoleGroupVO>();
		List<SelectedRoleGroupVO> selectedRoleGroupList=new ArrayList<SelectedRoleGroupVO>();
		//获取所有用户组
		//rolegroupList = roleGroupService.getAll();
		rolegroupList = roleGroupService.getAllWithoutCascade();
		List<RoleGroupVO> set = new ArrayList<RoleGroupVO>(rolegroupList);
		rolegroupList = new ArrayList<RoleGroupVO>(set);
		
		User currentUser = null ;
		List<RoleGroup> roleGroups = new ArrayList<RoleGroup>() ;
		if(id!=null && userDao.exists(id)){
			currentUser = userDao.get(id);
			roleGroups = roleGroupDao.getRoleGroupsByUserid(currentUser.getId());
		}
		
		ArrayList<Long> roleGroupIds =new ArrayList<Long>();
		
		//获取当前用户所在的用户组
		if (currentUser!=null && roleGroups != null) {			
			for (RoleGroup vo : roleGroups) {
				roleGroupIds.add(vo.getId());
			}
		}
		
		SelectedRoleGroupVO selectedRoleGroup=null ;
		for (RoleGroupVO Group : rolegroupList) {
			selectedRoleGroup=new SelectedRoleGroupVO();
			selectedRoleGroup.setRoleGroupVO(Group);
			if(roleGroupIds.contains(Group.getId())){
				selectedRoleGroup.setIsSelected(true);
			}else{
				selectedRoleGroup.setIsSelected(false);
			}
			selectedRoleGroupList.add(selectedRoleGroup);
		}
		return selectedRoleGroupList;
	}
	/**
	 *  从LdapServer获得用户信息
	 * @throws Exception 
	 *
	 */
    public UserVO getUserInfoFromLdapServer(String username) throws Exception{
    	User user=userDao.getUserInfoFromLdapServer(username);
    	return orikaBeanMapper.convert(user, UserVO.class);
    }
	/**
	 *  获得当前登录用户信息
	 */
    public UserVO getLoginUser(){
    	User user=SecurityUtil.getLoginUser();
    	UserVO userVo=null;
    	//userVo=(UserVO)orikaBeanMapper.convert(userDao.get(user.getId()), UserVO.class);
    	userVo=(UserVO)orikaBeanMapper.convert(user, UserVO.class);
    	return  userVo;  	
    }
    
    @SuppressWarnings("unchecked")
	public List<UserVO> getUsersByRoleGroupId(Long roleGroupId) {
        List<UserVO> result = new ArrayList<UserVO>();
        result = (List<UserVO>)orikaBeanMapper.convertList(userDao.getUsersByRoleGroupId(roleGroupId), entityVOClass);
        for(UserVO user:result){
            user.setRoleGroups(roleGroupService.getRoleGroupsByUserid(user.getId()));
            user.setRoles(roleService.getRolesByUserID(user.getId()));
        }
        return result;

    }
    
    @SuppressWarnings("unchecked")
    @Override
    public PageList<UserVO> getUserPageList(UserSO so){
        PageList<UserVO> result = new PageList<UserVO>();
        result = orikaBeanMapper.convertPageList(baseDao.getPageList(so), entityVOClass);
        for(UserVO vo:result.getList()){
            vo.setRoleGroups(orikaBeanMapper.convertList(roleGroupDao.getRoleGroupsByUserid(vo.getId()),RoleGroupVO.class));
        }
        return result;
    }
    /**
	 * 根据groupId删除CRM_USER_ROLE的记录
	 * @param groupId
	 */
	@Override
	public void removeUserRoleByRoleGroupId(Long groupId) {
		userDao.removeUserRoleByRoleGroupId(groupId);
	}
	 /**
	 * 根据groupId删除CRM_USER_ROLEGROUP的记录
	 * @param groupId
	 */
	@Override
	public void removeUserGroupByGroupId(Long groupId) {
		userDao.removeUserGroupByGroupId(groupId);
	}
    /**
     * 新建User_Role
     */
	@Override
	public void createUserRole(UserRoleMapping userRole) {
		userDao.createUserRole(userRole);
	}
	/**
     * 新建User_Group
     */
	@Override
	public void createUserGroup(UserGroupMapping userGroup) {
		userDao.createUserGroup(userGroup);
	}
	/**
	 * 密码重置
	 */
	@Override
	 public UserVO resetPassword( UserVO user ){
		user = get( user.getId() );
		String defaultpassword = Config.getUserDefaultResetPassword();
		if( StringUtils.isBlank( defaultpassword )){
			defaultpassword = "abc123";
		}
		String newPassword = passwordEncoder.encodePassword(defaultpassword.trim(), null);
		user.setPassword(newPassword);
		user = simpleUpdate(user);
		return user;
	}
}
